/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function (root) {
  if (!root) {
    return '';
  }
  const list = [];
  const postOrder = (node) => {
    if (!node) {
      return;
    }
    postOrder(node.left);
    postOrder(node.right);
    list.push(node.val);
  };
  postOrder(root);
  return list.join(' ');
};

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
var deserialize = function (data) {
  if (!data) {
    return null;
  }
  const list = data.split(' ').map((str) => parseInt(str));

  // 只要能判断弹出堆栈的节点是左节点还是右节点就能解决
  const bst = (min, max) => {
    if (!list.length) {
      return null;
    }
    const value = list.pop();
    //! 条件判断粗心了
    if (value < min || value > max) {
      list.push(value);
      return null;
    }
    const node = new TreeNode(value);

    node.right = bst(value, max);
    node.left = bst(min, value);
    return node;
  };
  return bst(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
};

/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */
